package com.trippin.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.trippin.DB.DBHandler;
import com.trippin.DB.entities.TripEntity;
import com.trippin.DB.entities.TripEntity.ShortDetailedTrip;
import com.trippin.Utils.ServletUtil;
import com.trippin.Utils.ServletUtilConstants;

@SuppressWarnings("serial")
public class TripServlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger(TripServlet.class.getCanonicalName());

	private static DBHandler dbHandlerInstance = DBHandler.INSTANCE;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, EntityNotFoundException, IOException {

		Action action = ServletUtil.getActionFromHeader(req,resp,LocationServlet.class.toString());		
		long userId = ServletUtil.getLongFromHeader(req, resp, ServletUtilConstants.USER_ID,
				TripServlet.class.toString(), action.getName());
		long tripId = -1;

		switch(action) {
		case GET_USER_TRIP:
		case UPDATE_TRIP:
		case DELETE_TRIP:
		case SEND_TRIP_SHARING_REQUEST:	
			tripId = ServletUtil.getLongFromHeader(req, resp, ServletUtilConstants.TRIP_ID,
					TripServlet.class.toString(), action.getName());
			break;
		}

		try{
			String bodyResponse = "";				
			switch(action) {
			case GET_USER_TRIP:
				bodyResponse = getTrip(userId, tripId);
				break;

			case GET_ALL_USER_TRIPS:
				bodyResponse = getAllTrips(userId);
				break;

			case CREATE_TRIP:
				bodyResponse = createNewTrip(userId, req);
				break;

			case UPDATE_TRIP:
				bodyResponse = updateTrip(userId, tripId, req);
				break;
				
			case DELETE_TRIP:
				dbHandlerInstance.deleteTrip(userId, tripId);
				break;
				
			case SEND_TRIP_SHARING_REQUEST:
				sendTripSharingRequest(userId, tripId, action.getName(), req, resp);
				break;

			default:
				ServletUtil.printError(resp,action.getName(), TripServlet.class.getName(), ServletUtilConstants.ERROR_WRONG_ACTION_NAME);
				break;
			}

			ServletUtil.createResponse(resp, action.getName(), bodyResponse);

		} catch(Exception e) {
			ServletUtil.printError(resp,action.getName(), TripServlet.class.getName(), e.getMessage());
			logger.log(Level.SEVERE,e.toString(), e);;
		}
	}

	private String updateTrip(long userId, long tripId, HttpServletRequest req) throws IOException {
		BufferedReader in = req.getReader();
		String reqBodyString = ServletUtil.getRequestBody(in);
		in.close();

		TripEntity trip = (TripEntity)ServletUtil.getFromJSON(reqBodyString, TripEntity.class);
		TripEntity tr = dbHandlerInstance.updateTrip(userId, tripId, trip);
		return ServletUtil.getResponseBody(tr);
	}

	private String createNewTrip(long userId, HttpServletRequest req) throws IOException {
		BufferedReader in = req.getReader();
		String reqBodyString = ServletUtil.getRequestBody(in);
		in.close();

		TripEntity trip = (TripEntity)ServletUtil.getFromJSON(reqBodyString, TripEntity.class);
		TripEntity tr = dbHandlerInstance.createTrip(userId, trip);
		return ServletUtil.getResponseBody(tr);
	}

	private String getTrip(long userId, long tripId) throws EntityNotFoundException, IOException {
		TripEntity trip = dbHandlerInstance.getUserTrip(userId,tripId);
		return ServletUtil.getResponseBody(trip);
	}


	private String getAllTrips(long userId) throws EntityNotFoundException, IOException {
		Iterable<ShortDetailedTrip> trips = dbHandlerInstance.getAllUserTrips(userId);
		return ServletUtil.getResponseBody(trips);
	}
	
	private void sendTripSharingRequest(long userId, long tripId, String actionName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		long shareWithId = ServletUtil.getLongFromHeader(req, resp, ServletUtilConstants.SHARE_WITH_ID,
				TripServlet.class.toString(), actionName);

		if((tripId > 0) && (shareWithId > 0)) {
			dbHandlerInstance.createTripSharingRequest(userId, tripId, shareWithId);
		}
		else {
			throw new IOException("missing required fileds in " + actionName + " request");
		}
	}

}
